package com.ply.flashsalessystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ply.flashsalessystem.entity.pojo.Goods;
import com.ply.flashsalessystem.entity.pojo.Tag;
import com.ply.flashsalessystem.entity.result.Result;
import com.ply.flashsalessystem.entity.status.GoodsPutAwayStatus;
import com.ply.flashsalessystem.entity.vo.manage.GoodsVO;
import com.ply.flashsalessystem.entity.wrapper.GoodsWrapper;
import com.ply.flashsalessystem.exception.GoodsException;
import com.ply.flashsalessystem.mapper.GoodsMapper;
import com.ply.flashsalessystem.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ply.flashsalessystem.service.TagService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XiaoPan
 * @since 2022-03-23
 */
@Service
@Slf4j
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    TagService tagService;

    /**
     * 增加 商品
     */
    @Override
    @Transactional
    public boolean addGoods(Goods goods) {
        //优化 这里 会出现异常  向前端 反应 异常的产生 以及解决 name,tag_id,put_away
        if (nameAndTagIdAnd(goods.getGoodsId(), goods.getName(), goods.getTagId())) {
            throw new GoodsException("商品name重复或分类不存在");
        }
        // 默认 商品 未上架
        goods.setPutAway(GoodsPutAwayStatus.NO_AWAY);
        goods.setGoodsId(null);
        return goodsMapper.insert(goods) != 0;
    }

    /**
     * 修改商品
     */
    @Override
    @Transactional
    public boolean updateGoods(Goods goods) {
        if (nameAndTagIdAnd(goods.getGoodsId(), goods.getName(), goods.getTagId())) {
            throw new GoodsException("商品name重复或分类不存在");
        }

        /*
        价格 数量
         */
        paGoodsMes(goods);

        //上下架
        if (!GoodsPutAwayStatus.NO_AWAY.equals(goods.getPutAway()) && !GoodsPutAwayStatus.DO_AWAY.equals(goods.getPutAway())) {
            throw new GoodsException("上下架状态出错");
        }

        //图片不可以在在这里更改
        Goods goods1 = goodsMapper.selectById(goods.getGoodsId());
        goods.setImage(goods1.getImage());

        // 和增加一样会出现异常
        return goodsMapper.updateById(goods) != 0;
    }

    @Override
    public boolean deleteGoodsById(Long id) {
        return false;
    }

    @Override
    public Page<GoodsVO> queryGoodsAll(Integer current, Integer limit, GoodsWrapper goodsWrapper) {
        return goodsMapper.queryGoodsAllPage(new Page<>(current, limit), goodsWrapper);
    }

    /**
     * 条件 分页 查询 商品
     *
     * @param current      当前页
     * @param limit        当前页数量
     * @param goodsWrapper 查询条件
     */
    @Override
    public Result queryGoodsAllPageByOdds(long current, long limit, GoodsWrapper goodsWrapper) {

        Page<Goods> page = new Page<>(current, limit);

        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(goodsWrapper.getName())) {
            queryWrapper.like("name", goodsWrapper.getName());
        }
        if (!(StringUtils.isEmpty(goodsWrapper.getTagId()))) {
            queryWrapper.eq("tagId", goodsWrapper.getTagId());
        }
        if (!(StringUtils.isEmpty(goodsWrapper.getMinPrice()))) {
            queryWrapper.ge("price", goodsWrapper.getMinPrice());
        }

        if (!(StringUtils.isEmpty(goodsWrapper.getMaxPrice()))) {
            queryWrapper.le("price", goodsWrapper.getMaxPrice());
        }

        //  剩下的条件还可以补充
        Page<Goods> page1 = this.page(page, queryWrapper);
        return Result.ok().data("total", page.getTotal()).data("rows", page1.getRecords());
    }

    /**
     * 更新商品数量
     */
    @Override
    public boolean updateGoodsNums(Integer goodsId, double nums) {
        if (goodsMapper.selectById(goodsId) == null) {
            throw new GoodsException("商品id 错误");
        }
        return goodsMapper.updateNums(goodsId, nums) != 0;
    }

    //上架商品
    @Override
    public boolean putAwayGoods(Integer goodId) {
        Goods goods = goodsMapper.selectById(goodId);
        if (goods == null) {
            throw new GoodsException("商品id 出错");
        }
        //上架的条件
        paGoodsMes(goods);
        if (Objects.equals(goods.getPutAway(), GoodsPutAwayStatus.DO_AWAY)) {
            throw new GoodsException("商品 已经上架了 不可以 在上架了");
        }
        return goodsMapper.updatePutAway(goodId, GoodsPutAwayStatus.DO_AWAY) != 0;
    }

    //下架商品
    @Override
    public boolean outAwayGoods(Integer goodId) {
        Goods goods = goodsMapper.selectById(goodId);
        if (goods == null) {
            log.debug("商品id 出错");
            throw new GoodsException("商品id 出错");
        }

        if (Objects.equals(goods.getPutAway(), GoodsPutAwayStatus.NO_AWAY)) {
            log.debug("商品 已经下架了 不可以 在下架了");
            throw new GoodsException("商品 已经下架了 不可以 在下架了");
        }
        return goodsMapper.updatePutAway(goodId, GoodsPutAwayStatus.NO_AWAY) != 0;
    }


    /**
     * 判断 商品name 分类id 是否存在
     *
     * @return false 表示name 不存在   tagId 存在
     */
    private boolean nameAndTagIdAnd(Integer goodId, String name, Integer tagId) {
        log.info("判断商品name 和 tagid 是否存在");
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);

        Goods goods = goodsMapper.selectOne(queryWrapper);
        if (goods != null && !Objects.equals(goods.getGoodsId(), goodId)) {
            log.info("商品name 存在");
            return true;
        }
        QueryWrapper<Tag> tag = new QueryWrapper<>();
        tag.eq("tag_id", tagId);
        if (tagService.getOne(tag) == null) {
            log.info("tagId 不存在");
            return true;
        }
        return false;
    }

    //上架 判断
    private void paGoodsMes(Goods goods) {
        //余量 小于等于 0 不允许 上架
        double remainNums = goods.getRemainNums();

        //价格 小于等于 0 不允许 上架
        double price = goods.getPrice();

        //最少售卖量 小于等于 0 不允许 上架
        double minSales = goods.getMinSales();

        //商品 描述 必须要有 才能上架
        String details = goods.getDetails();

        if (remainNums < 0 || price < 0 || minSales < 0 || details == null || details.equals("")) {
            throw new GoodsException("商品 上架 错误, 请检查 余量 价格 最少售卖量 都必须大于0, 且 商品描述 必须有");
        }
    }
}

